package com.gxz.job.example.job;

import com.gxz.job.example.service.OrderService;
import com.gxz.job.elasticjob.start.zookeeper.annotation.ElasticSimpleJob;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

//@Component
@ElasticSimpleJob(jobName = "orderSummarySimpleJob",corn = "0 24 22 * * ?",shardingTotalCount = 24,overwrite = true)
public class OrderSummarySimpleJob implements SimpleJob {
    @Autowired
    private OrderService orderService;
    @Override
    public void execute(ShardingContext shardingContext) {
        //1.获取分片项
        int item = shardingContext.getShardingItem();
        //2.将前一天日期，拆分成24个时间段. 00 01 02 。。
        //2.1 前一天日期0点
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH,-1);
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        //2.2 基于0点，+1小时
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            Date date = DateUtils.addHours(calendar.getTime(), i);
            dateList.add(date);
        }
        //3.每一个分片，统计一个时间段订单信息。
        //eg: 0    00 01
        //eg: 1    01 02
        //...
        Date date = dateList.get(item);
        Date endDate = DateUtils.addHours(date, 1);
        orderService.countOrder(date,endDate);
    }
}
